import socket
from time import ctime

HOST = 'localhost'
PORT = 12455
BUFSIZ = 1024
ADDR = (HOST, PORT)


class BreakAllError(RuntimeError):
    def __init__(self, args):
        self.args = args


def start():
    ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ts.bind(ADDR)
    ts.listen(5)

    try:
        while True:
            print('waiting for connect...')
            conn, addr = ts.accept()
            print('connect from:' + str(addr))
            while True:
                data = conn.recv(BUFSIZ)
                if not data:
                    break
                if data.decode('utf-8') == 'exit':
                    raise BreakAllError('break all')

                print(data.decode('utf-8'))
                conn.send(('[%s] %s' % (ctime(), data)).encode('utf-8'))
    except BreakAllError as e:
        print(str(e.args))


if __name__ == "__main__":
    start()
